/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pbl_cliente;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Tayane
 */
public class RecebeMsgMulticast implements Runnable{
    
    private static String grupo;
    private static int porta;
    private CotaChat cotaChat;
    
    public RecebeMsgMulticast(String ipMulticast, int portaMulticast, CotaChat cotaChat){
        this.grupo = ipMulticast;
        this.porta = portaMulticast;
        this.cotaChat = cotaChat;
    }  
    public void run(){
        while(true){
            try {
                System.out.println("IpMulticast: " + grupo + " Porta: " + porta);
                MulticastSocket s = new MulticastSocket(porta);
                s.joinGroup(InetAddress.getByName(grupo));
                byte buf[] = new byte[512];
                DatagramPacket pack  = new DatagramPacket(buf, buf.length);
                s.receive(pack);
                String data = new String (pack.getData());
                System.out.println(data);
                String msg = data.split("§")[0];
                this.cotaChat.notifica(msg);               
            } catch (IOException ex) {
                Logger.getLogger(RecebeMsgMulticast.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("Erro em recebe mensagens Multicast");
                System.out.println("Erro: " + ex.getMessage());
            }
        }
    }
}
